﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using Sunlight.Manage.Common.BaseCore.Entity.DTO;
using Sunlight.Manage.Common.Result;
using Sunlight.Manage.Common.ValidateRules;
using System.Reflection;

namespace Sunlight.Manage.MentApi.Utility.Filters
{

    /// <summary>
    /// 参数校验
    /// </summary>
    public class CustomAsyncValidateParaActionFilterAttribute : Attribute, IAsyncActionFilter
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            List<object?> parameterList = context.ActionArguments
                .Where(p => p.Value is BaseDTO && p.Value is not null)
                .Select(c => c.Value).ToList();

            List<(bool, string?)> messagList = new List<(bool, string?)>();
            foreach (var parameter in parameterList) {

                //实体验证的实现--通过特性
                foreach (var prop in parameter.GetType().GetProperties().Where(p => p.IsDefined(typeof(BaseAbstractAttribute),true))) {

                    BaseAbstractAttribute attribute=prop.GetCustomAttribute<BaseAbstractAttribute>();
                    messagList.Add(attribute.DoValidate(prop.GetValue(parameter)));
                }
            }

            if (messagList.Any(c => c.Item1 == false))
            {
                context.Result = new JsonResult(new ApiDataResult<string>()
                {
                    Success = false,
                    Message = string.Join(",", messagList.Where(c => c.Item1 == false).Select(c => c.Item2))
                });
            }
            else { 
               await next(); 
            }

        }

    }
}
